package site.teamo.biu.net.common.util;

import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.*;
import jakarta.servlet.http.HttpServletRequest;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author haocongshun
 * @date 2023/03/03 11:13:43
 */
public class HttpUtils {
    private HttpUtils() throws IllegalAccessException {
        throw new IllegalAccessException("HttpUtils 不支持实例化");
    }


    public static HostPort getHostPort(HttpRequest request) {
        String uri = request.uri();
        if (uri.startsWith("http://") || uri.startsWith("https://")) {
            try {
                URL url = new URL(uri);
                return HostPort.of(url.getHost(), url.getPort() == -1 ? 80 : url.getPort());
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("Get HostPort failed for " + request.uri());
            }
        } else {
            String host = uri.contains(":") ? uri.substring(0, uri.lastIndexOf(":")) : uri;
            int port = uri.contains(":") ? Integer.parseInt(uri.substring(uri.lastIndexOf(":") + 1)) : 80;
            return HostPort.of(host, port);
        }
    }

    public static HttpResponse forbiddenResponse() {
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
    }

    public static HttpResponse okResponse() {
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    }

    public static Object convertHttpRequestToOriginalMsg(HttpRequest request) {
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(new HttpRequestEncoder());
        embeddedChannel.writeOutbound(request);
        final Object msg = embeddedChannel.readOutbound();
        embeddedChannel.close();
        return msg;
    }

    public static String getBaseUrl(HttpServletRequest request) {
        return request.getRequestURL().toString().replace(request.getRequestURI(), "");
    }
}
